<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 触发高频事件 N 秒内执行一次 

        // 时间戳执行

        function throttle(func, wait) {
            var context, args;
            var previous = 0;
            return function () {
                var now = Date.now();
                context = this;
                args = arguments;
                if (now - previous > wait) {
                    func.apply(context, args);
                    previous = now;
                }

            }
        }
        // leading 是否立即执行
        // trailing 结束调用时 是否要执行
        // 取消功能
        function throttle1(func, wait, option) {
            var context, args, previous;

            if (option.leading) {
                previous = 0;
            } else {
                previous = Date.now();
            }
            // 结束调用时,有可能需要调用的函数
            var later = function () {
                timer = null;
                func.apply(context, args);
                previous = option.leading ? 0 : Date.now();
                context = args = null;
            }

            var throttled = function () {
                var now = Date.now();
                context = this;
                args = arguments;
                // 主要用于 结束调用时,知道距离 wait 还有多少时间 以便 开启定时器,让最后一次执行成功
                var remaining = wait - (now - previous);

                if (remaining <= 0 || remaining > wait) {
                    if (timer) {
                        clearTimeout(timer)
                        timer = null
                    }
                    func.apply(context, args);
                    previous = now;
                    if (!timer) {
                        context = args = null;
                    }
                } else if (!timer && option.trailing != false) {
                    setTimeout(later, remaining)
                }

            }

            return throttled;

        }
    </script>
</body>

</html>